package com.building18.controller;

import com.alibaba.fastjson2.JSON;
import com.building18.handler.MyAssert;
import com.building18.pojo.MyPageData;
import com.building18.pojo.Result;
import com.building18.pojo.User;
import com.building18.pojo.dto.EditUserDTO;
import com.building18.pojo.dto.UserDTO;
import com.building18.pojo.enums.BuildingCode;
import com.building18.pojo.enums.Code;
import com.building18.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.collections4.Get;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户管理")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/{pageNum}/{pageSize}")
    @Operation(summary = "分页查询用户")
    public Result<?> selectUser(@PathVariable Integer pageNum, @PathVariable Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<User> users =userService.selectUser();
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        MyPageData myPageData=new MyPageData(userPageInfo.getTotal(),userPageInfo.getList());
        return Result.ok(myPageData, Code.SELECT_SUCCESS.getMessage());
    }

    @PostMapping("/updateUser")
    @Operation(summary = "更新用户信息")
    public Result<?> updateUser(@RequestBody User user){
        Integer i = userService.updateUser(user);
        MyAssert.error(i<=0, Code.UPDATE_FAIL.getMessage());
        return Result.ok(Code.UPDATE_SUCCESS.getMessage());
    }


    @DeleteMapping("/deleteUser/{id}")
    @Operation(summary = "删除用户信息")
    public Result<?> deleteUser(@PathVariable Integer id){
        Integer i = userService.deleteUser(id);
        MyAssert.error(i<=0, Code.DELETE_FAIL.getMessage());
        return Result.ok(i,Code.DELETE_SUCCESS.getMessage());
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<User> login(
            @RequestBody UserDTO userDTO,
            HttpServletRequest request,  //获取session
            HttpServletResponse response //获取cookie
    ) {

        User user = userService.login(userDTO);

        //存session
        HttpSession httpSession = request.getSession(); // 显式获取Session对象
        httpSession.setAttribute("user", user);

        //打印Session信息
        System.out.println("Session ID: " + httpSession.getId());
        System.out.println("Session中存储的用户: " + httpSession.getAttribute("user"));
        System.out.println("Session创建时间: " + new Date(httpSession.getCreationTime()));
        System.out.println("Session失效时间: " + new Date(httpSession.getLastAccessedTime() + httpSession.getMaxInactiveInterval() * 1000));

        //存cookie
        if (userDTO.isRememberMe()) {
            String jsonUser = JSON.toJSONString(user);
            String encodeUser = URLEncoder.encode(jsonUser, StandardCharsets.UTF_8);
            Cookie cookie = new Cookie("user", encodeUser);
            cookie.setPath("/");
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
        }

        return Result.ok(user, Code.LOGIN_SUCCESS.getMessage());
    }

    @GetMapping("/getUserData")
    @Operation(summary = "获取用户的session数据")
    public Result<?> getUserData(HttpSession session) {
        Object user = session.getAttribute("user");
        MyAssert.error(user==null,Code.LOGIN_COOKIE_FAIL.getMessage());
        System.out.println(user);
        return Result.ok(user,Code.SELECT_SUCCESS.getMessage());
    }

    @GetMapping("/beforeDeleteRole/{id}")
    @Operation(summary = "删除角色前查询")
    public Result<?> beforeDeleteRole(@PathVariable("id") Integer id) {
        userService.beforeDeleteRole(id);
        return Result.ok(Code.CAN_DELETE.getMessage());
    }

    @PutMapping("/updateUserPassword")
    @Operation(summary = "修改用户信息")
    public Result<?> updateUserData(@RequestBody EditUserDTO dto, HttpServletRequest request, HttpServletResponse response) throws IOException {
       Integer i = userService.updateUserData(dto);
       MyAssert.error(i <= 0, Code.WRONG_OLD_PASSWORD.getMessage());
        // 清空session和cookie
        clearUser(request, response);

//        response.setContentType("application/json;charset=UTF-8");
//        response.setStatus(600);
//        response.getWriter().write("{\"code\":600,\"msg\":\"请使用新密码重新登录....\"}");

        return Result.ok(i,Code.UPDATE_SUCCESS.getMessage());
    }

    @GetMapping("/logOut")
    public Result<?> logOut(HttpServletRequest request, HttpServletResponse response) {
        clearUser(request, response);
        return Result.ok( Code.LOGOUT.getMessage());
    }


    //清空方法
    private void clearUser(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute("user");
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    cookie.setMaxAge(0);
                    cookie.setValue(null);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
    }

}
